package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.StudentBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

public class JsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        List<StudentBean> studentBeans = List.of(
                new StudentBean(1,"上三","14474777",LocalDate.parse("2001-02-03")),
                new StudentBean(2,"黄强","14215211",LocalDate.parse("2005-02-03")),
                new StudentBean(3,"黄伟","13581254",LocalDate.parse("2004-02-03")),
                new StudentBean(4,"丁昂","14425111",LocalDate.parse("2005-06-01"))
        );
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
//        String jsonStr = mapper.writeValueAsString(studentBeans);
//        resp.getWriter().print(jsonStr);
        mapper.writeValue(resp.getWriter(),studentBeans);
    }
}
